package fr.demos.cinepantin.dao.impl;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.UserTransaction;

import fr.demos.cinepantin.Admin;
import fr.demos.cinepantin.Article;
import fr.demos.cinepantin.Client;
import fr.demos.cinepantin.dao.DaoAdmin;
import fr.demos.cinepantin.dao.interfac.AdminDao;
import fr.demos.cinepantin.exception.DaoExceptions;

@DaoAdmin
public class AdminDaoImpl implements AdminDao {
	// Grace a l'injection l'objet entityManager est instancie
		@PersistenceContext(unitName = "cinemarc")
		private EntityManager em; // gestion des entity qui sont dans un contexte
		@Resource
		private UserTransaction ut;

		public AdminDaoImpl() {

		}
		
		@Override
		public void enregistrerAdmin(Admin admin) throws DaoExceptions {
			try {
				ut.begin();
			} catch (Exception e) {
				e.printStackTrace();
			}

			em.persist(admin);

			try {
				ut.commit();
			} catch (Exception e) {
				e.printStackTrace();
				throw new DaoExceptions(e.getMessage(), e);
			}				
		}

	@Override
	public boolean verifLoginAdmin(String email, String password)
			throws DaoExceptions {
		String query = "SELECT a FROM Admin a WHERE";
		query+=	" a.email = '"+ email + "' AND a.password = '" + password + "'";
		TypedQuery<Admin> q = em.createQuery(query, Admin.class);
		System.out.println(email+ " " + password + " " + q.getResultList().isEmpty());

		if(q.getResultList().isEmpty()){
			return false;
		}
		return true ;		
	}
	
	

	@Override
	public Admin getAdminByEmail(String email) throws DaoExceptions {
		String query = "SELECT a FROM Admin a WHERE";
		query+=	" a.email = '"+ email + "'";
		TypedQuery<Admin> q = em.createQuery(query, Admin.class);

		return q.getSingleResult();

	}

	@Override
	public Admin getAdminById(int id) throws DaoExceptions {
		Admin admin = null;
		admin = em.find(Admin.class, id);

		return admin;

	}

	}
	


